﻿/** 
 *Author:       lang
 *Date:         2017
 *Description:  自动生成窗体资源配置json
*/

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace MotionFramework.Editor
{
    [Serializable]
    internal class KeyValuesInfo
    {
        //配置信息
        public List<KeyValuesNode> ConfigInfo;
    }

    [Serializable]
    internal class KeyValuesNode
    {
        //键
        public string Key;

        //值
        public string Value;
    }

    public class UIKitWindowConfigSetting : ScriptableObject
    {
        [SerializeField]
        string m_WindowPath;

        public const string WindowConfFile = "Assets/ResourcesHot/Config/UIWindowConfigInfo.json";
        public const string WindowConfSettingFile = "Assets/MotionFramework/UIKitSetting/UIKitWindowConfigSetting.asset";

        public string WindowPath => m_WindowPath;

        [MenuItem("MotionTools/创建窗体配置路径", false, 100)]
        static void CreateWindowConfigSetting()
        {
            string[] paths = AssetDatabase.FindAssets("t:UIKitWindowConfigSetting");
            if (paths.Length >= 1)
            {
                string path = AssetDatabase.GUIDToAssetPath(paths[0]);
                EditorUtility.DisplayDialog("警告", $"已存在UIKitWindowConfigSetting，路径:{path}", "确认");
                return;
            }
        
            UIKitWindowConfigSetting setting = CreateInstance<UIKitWindowConfigSetting>();
            string dirPath = System.IO.Path.GetDirectoryName(WindowConfSettingFile);
			if (!System.IO.Directory.Exists(dirPath))
                System.IO.Directory.CreateDirectory(dirPath);
            AssetDatabase.CreateAsset(setting, WindowConfSettingFile);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        [MenuItem("MotionTools/创建窗体配置", false, 101)]
        static void CreateWindowConfig()
        {
            UIKitWindowConfigSetting m_Setting;

            if (!File.Exists(WindowConfSettingFile))
                CreateWindowConfigSetting();

            string[] paths = AssetDatabase.FindAssets("t:UIKitWindowConfigSetting");
            if (paths.Length == 0)
            {
                Debug.LogError("不存在UIKitWindowConfigSetting");
                return;
            }
            if (paths.Length > 1)
            {
                Debug.LogError("UIKitWindowConfigSetting数量大于1");
                return;
            }
            string path = AssetDatabase.GUIDToAssetPath(paths[0]);
            m_Setting = AssetDatabase.LoadAssetAtPath<UIKitWindowConfigSetting>(path);
            string windowPath = m_Setting.WindowPath;

            if (string.IsNullOrEmpty(windowPath))
            {
                Debug.LogError("WindowPath 路径为空请检查");
                return;
            }

            if (!Directory.Exists(windowPath))
            {
                Debug.LogError($"WindowPath[{windowPath}] 路径不存在");
                return;
            }

            var files = Directory.GetFiles(windowPath, "*.prefab", SearchOption.AllDirectories);
            if (files.Length == 0)
            {
                Debug.Log("没有要更新的预制体");
                return;
            }

            KeyValuesInfo keyValues = new KeyValuesInfo();
            keyValues.ConfigInfo = new List<KeyValuesNode>(files.Length);

            foreach (var file in files)
            {
                string key = Path.GetFileNameWithoutExtension(file);
                string val = Path.GetDirectoryName(file);
                val = ToRelativeAssetPath(val);
                val = $"{val}/{key}";

                keyValues.ConfigInfo.Add(new KeyValuesNode
                {
                    Key = key,
                    Value = val
                });
            }

            string jsonString = JsonUtility.ToJson(keyValues);
            try
            {
                string windowConfDir = Path.GetDirectoryName(WindowConfFile);
                if (!Directory.Exists(windowConfDir))
                    Directory.CreateDirectory(windowConfDir);

                File.WriteAllText(WindowConfFile, jsonString);
            }
            catch (Exception e)
            {
                Debug.LogError("写入json文件失败：" + e.Message);
                return;
            }

            AssetDatabase.Refresh();

            Debug.LogFormat("已更新{0}个，路径：{1}", files.Length, WindowConfFile);
        }

        static string ToRelativeAssetPath(string s)
        {
            string token = "ResourcesHot/";
            s = s.Replace("\\", "/");
            return s.Substring(s.IndexOf(token) + token.Length);
        }
    }
}